package com.example.moonshine.zxing.Activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.moonshine.zxing.Data.ListData;
import com.example.moonshine.zxing.Data.PostlistData;
import com.example.moonshine.zxing.Data.SidSelectData;
import com.example.moonshine.zxing.Hepler.DataDBHepler;
import com.example.moonshine.zxing.R;
import com.example.moonshine.zxing.Util.SavePamasInfo;
import com.github.zackratos.ultimatebar.UltimateBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * Created by moonshine on 2018/2/8.
 */

public class Scoplist extends Activity {
    @SuppressLint("MissingSuperCall")
    ArrayList postlist = new ArrayList();
    ListView listView;
    PostAdapter postAdapter;
    String sysids=null;
    DataDBHepler dbHepler;
    String[] sysIdPotion=new String[]{};
    String[] sysname=new String[]{};
    String sysId=null;
    SavePamasInfo mSavePamasInfo = new SavePamasInfo();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.axtivity_saomiao);
        UltimateBar.newColorBuilder()
                .statusColor(Color.parseColor("#16abd9"))       // 状态栏颜色
                .statusDepth(50)                // 状态栏颜色深度
                .build(this)
                .apply();
        listView = super.findViewById(R.id.list_Saoitem);

        dbHepler = new DataDBHepler(getBaseContext());
        if (dbHepler.isIdorSid())
        {
            ArrayList<SidSelectData> DataList = dbHepler.FindSidData();
            final SidSelectData data = new SidSelectData(DataList.get(0).getId(),DataList.get(0).getId(),DataList.get(0).getSysids());
            sysids = data.getSysids();
            Log.i(TAG,"sysids:"+sysids);
            sysIdPotion = sysids.replace("[","").replace("]","").split(",");

        }
        sysname=mSavePamasInfo.getInfo(this,"sysname","login").split(",");
        ImageView imageView = findViewById(R.id.call_view);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("index","0");
                intent.setClass(Scoplist.this,MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
        initSpinner();
        final RefreshLayout refreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                try {
                    init();
                    Toast.makeText(Scoplist.this, "刷新成功", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishRefresh(true/*,false*/);//传入false表示刷新失败
                } catch (Exception e) {
                    e.printStackTrace();
                    refreshlayout.finishRefresh(false/*,false*/);//传入false表示刷新失败
                    Toast.makeText(Scoplist.this, "刷新失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(true/*,false*/);//传入false表示加载失败
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
//        refreshLayout.setRefreshHeader(new BezierRadarHeader(this).setEnableHorizontalDrag(true));
//设置 Footer 为 球脉冲 样式
//        refreshLayout.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
    }


    public void initSpinner() {
        final Spinner sp;
        sp = findViewById(R.id.TD_Spinner);
        final String[] list = new String[sysname.length];
        for (int i=0; i<sysname.length;i++)
        {
            String sting = sysname[i];
            list[i]=sting;
            Log.i(TAG, "数据为"+sting);
        }
        //第二步：为下拉列表定义一个适配器，这里就用到里前面定义的list。
        final ArrayAdapter<String> listadapter = new ArrayAdapter<String>(this, R.layout.spinner_text, list);
        //为适配器设置下拉列表下拉时的菜单样式。
        listadapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
        //将适配器添加到下拉列表上
        sp.setAdapter(listadapter);
        //为下拉列表控框定义点击，这个时间相应，菜单被点中
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView)view;
                tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
                tv.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                Log.i(TAG, "位置" + position);
                StringBuffer sb = new StringBuffer();
                if (position==0)
                {
                    for (int i = 0; i < sysIdPotion.length; i++) {
                        sb.append(sysIdPotion[i]);
                        if (i<sysIdPotion.length-1) {
                            sb.append(",");
                        }
                    }
                    sysId = sb.toString();
                    Log.i("tag","sysId"+sysId);
                }else
                {
                    sysId = sb.append(sysIdPotion[position-1]).toString();
                }
                listadapter.notifyDataSetChanged();
                postlist.clear();
                initView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void initView(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            new AnotherTask().execute("");
        }
    }).start();
    postAdapter = new PostAdapter(getBaseContext(), postlist);
    listView.setAdapter(postAdapter);
}
    public void init(){
        postlist.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                new AnotherTask().execute("");
            }
        }).start();
    }

    @SuppressLint("StaticFieldLeak")
    private class AnotherTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPostExecute(String result) {
            //对UI组件的更新操作
            Gson gson = new Gson();
            List<ListData> listData = null;
            try {
                PostlistData postlistData = gson.fromJson(result,PostlistData.class);
                listData = postlistData.getValues();
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                Log.i("tag","异常"+e);
            }
            if (listData.size()!=0) {
                for (int i = 0; i < listData.size(); i++) {
                    String id = listData.get(i).getTarget_id();
                    String name = listData.get(i).getEvent_name();
                    String time = listData.get(i).getEvent_date().substring(0,9);
                    ListData p = new ListData(id, name, time);
                    postlist.add(p);
                }
            }else {
                Toast.makeText(getApplicationContext(),"暂无扫描记录",Toast.LENGTH_SHORT).show();
            }
            try{
                postAdapter.notifyDataSetChanged();
            }catch (Exception e){
                Log.e(TAG, "postlisthttp: ",e );
            }
        }
        @Override
        protected String doInBackground(String... params) {
            //耗时的操作
            String url = "http://119.23.219.22:80/element/find-event";

            if (sysids.equals(""))
            {
                sysids="sysids";
            }
            Gson gson =new Gson();
            OkHttpClient client = new OkHttpClient();
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            FormBody body = new FormBody.Builder()
                    .add("sysids",sysids.replace("[","").replace("]",""))
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            String result ="";
            Log.i("tag","tag"+sysids.replace("[","").replace("]",""));
            try {
                Response response = client.newCall(request).execute();
                //获取后台传输的额status状态码
                result = response.body().string();

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground: ",e );
            }
            return result;

        }
    }

    public class PostAdapter extends BaseAdapter {

        private ArrayList<ListData> List;
        private Context context;

        PostAdapter(Context context, ArrayList<ListData> list) {
            this.context = context;
            this.List = list;
        }

        @Override
        public int getCount() {
            return List.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = view.inflate(context, R.layout.activity_set_item, null);
            }

            TextView tv = view.findViewById(R.id.set_item_id);
            TextView tv1 = view.findViewById(R.id.set_item_name);
            TextView tv2 = view.findViewById(R.id.set_item_time);

            ListData data = List.get(position);
            tv.setText(data.getTarget_id());
            tv1.setText(data.getEvent_name());
            tv2.setText(data.getEvent_date());
            return view;
        }
    }
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.down_in, R.anim.down_out);
    }
}
